package com.situ.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageInfo;
import com.situ.bean.APIResult;
import com.situ.bean.Project;
import com.situ.service.ProjectService;

@RestController
@RequestMapping("/api/projects")
@CrossOrigin(origins = { "http://127.0.0.1:8848" })
public class ProjectController {

	@Autowired
	private ProjectService projectService;

	@GetMapping()
	public APIResult get(Integer page, Integer limit, Project project) {
		PageInfo info = projectService.getByPage(page, limit, project);
		APIResult apiResult = new APIResult();
		if (info.getTotal() > 0) {
			apiResult.setStatus(200);
			apiResult.setData(info);
		} else {
			apiResult.setStatus(404);
			apiResult.setMsg("未查询到任何记录！！");
			apiResult.setData(info);
		}
		return apiResult;
	}

	@PostMapping
	public APIResult add(@RequestBody Project project) {
		project = projectService.add(project);
		APIResult apiResult = new APIResult();
		apiResult.setStatus(201);
		apiResult.setData(project);
		return apiResult;
	}

	@DeleteMapping()
	public APIResult remove(Integer id) {
		Project project = projectService.remove(id);
		APIResult apiResult = new APIResult();
		if (project != null) {
			apiResult.setStatus(204);
			apiResult.setData(project);
		} else {
			apiResult.setStatus(404);
			apiResult.setMsg("删除的项目不存在");
		}
		return apiResult;
	}

	@PutMapping()
	public APIResult edit(@RequestBody Project project) {
		project = projectService.edit(project);
		APIResult apiResult = new APIResult();
		if (project != null) {
			apiResult.setStatus(201);
			apiResult.setData(project);
		} else {
			apiResult.setStatus(404);
			apiResult.setMsg("修改的项目不存在");
		}
		return apiResult;

	}
}
